<template>
  <div class="registration-page">
    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" inline>
        <el-form-item label="水库名称">
          <el-input
            v-model="queryForm.reservoirName"
            placeholder="请输入水库名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="水库等级">
          <el-select
            v-model="queryForm.level"
            placeholder="请选择水库等级"
            clearable
            style="width: 150px"
          >
            <el-option label="一等" value="一等" />
            <el-option label="二等" value="二等" />
            <el-option label="三等" value="三等" />
            <el-option label="四等" value="四等" />
            <el-option label="五等" value="五等" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择管理状态"
            clearable
            style="width: 120px"
          >
            <el-option label="正常" value="normal" />
            <el-option label="维护中" value="maintenance" />
            <el-option label="停用" value="disabled" />
            <el-option label="报废" value="decommissioned" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="operation-card" shadow="never">
      <el-button type="primary" @click="handleAdd">新增注册</el-button>
      <el-button
        type="danger"
        :disabled="!selectedRows.length"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
      <el-button type="success" @click="handleExport">导出数据</el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="注册编号" width="120" />
        <el-table-column prop="reservoirName" label="水库名称" width="150" />
        <el-table-column prop="level" label="水库等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)">
              {{ row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="地理位置" min-width="200" show-overflow-tooltip />
        <el-table-column prop="capacity" label="库容(万m³)" width="120" />
        <el-table-column prop="manager" label="管理单位" width="150" show-overflow-tooltip />
        <el-table-column prop="contact" label="联系人" width="100" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="registrationDate" label="注册日期" width="120" />
        <el-table-column prop="status" label="管理状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" icon="View" @click="handleView(row)">查看</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <RegistrationFormDialog
      v-model:visible="dialogVisible"
      :form-data="currentRow"
      :is-view="isView"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RegistrationFormDialog from './components/RegistrationFormDialog.vue'

// 查询表单
const queryForm = reactive({
  reservoirName: '',
  level: '',
  status: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const currentRow = ref(null)
const isView = ref(false)

// 获取等级标签样式
const getLevelTagType = (level: string) => {
  const levelMap = {
    '一等': 'danger',
    '二等': 'warning',
    '三等': 'primary',
    '四等': 'success',
    '五等': 'info'
  }
  return levelMap[level] || 'info'
}

// 获取状态标签样式
const getStatusTagType = (status: string) => {
  const statusMap = {
    normal: 'success',
    maintenance: 'warning',
    disabled: 'info',
    decommissioned: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    normal: '正常',
    maintenance: '维护中',
    disabled: '停用',
    decommissioned: '报废'
  }
  return statusMap[status] || status
}

// 模拟API - 获取水库注册列表
const fetchRegistrationList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const mockData = [
      {
        id: 1,
        code: 'REG2024001',
        reservoirName: '青山水库',
        level: '三等',
        location: '福建省莆田市城厢区',
        capacity: 1250.5,
        manager: '莆田市水利局',
        contact: '张三',
        phone: '13800138001',
        registrationDate: '2024-01-15',
        status: 'normal',
        buildYear: '1985',
        damHeight: 45.2,
        damLength: 320,
        catchmentArea: 125.8,
        purpose: '防洪、灌溉、供水',
        remark: '重要水利设施'
      },
      {
        id: 2,
        code: 'REG2024002',
        reservoirName: '白云水库',
        level: '四等',
        location: '福建省莆田市荔城区',
        capacity: 680.3,
        manager: '荔城区水务局',
        contact: '李四',
        phone: '13800138002',
        registrationDate: '2024-02-10',
        status: 'maintenance',
        buildYear: '1992',
        damHeight: 32.5,
        damLength: 280,
        catchmentArea: 89.6,
        purpose: '灌溉、供水',
        remark: '正在进行大坝维护'
      }
    ]
    let list = [...mockData]
    if (list.length < 10) {
      const target = Math.floor(Math.random() * 41) + 10
      const templates = mockData
      while (list.length < target) {
        const base: any = templates[list.length % templates.length]
        const idx = list.length + 1
        list.push({
          ...base,
          id: idx,
          code: `REG${new Date().getFullYear()}${String(idx).padStart(3, '0')}`,
          reservoirName: `${base.reservoirName}-${idx}`,
          status: ['normal', 'maintenance', 'disabled', 'decommissioned'][idx % 4],
          phone: '1380013' + String(801 + idx).padStart(3, '0')
        })
      }
    }
    tableData.value = list
    pagination.total = list.length
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 模拟API - 删除水库注册
const deleteRegistration = async (ids: number[]) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    ElMessage.success('删除成功')
    fetchRegistrationList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 模拟API - 导出数据
const exportRegistration = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  fetchRegistrationList()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    reservoirName: '',
    level: '',
    status: '',
    dateRange: []
  })
  handleQuery()
}

// 新增
const handleAdd = () => {
  currentRow.value = null
  isView.value = false
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  currentRow.value = { ...row }
  isView.value = false
  dialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  currentRow.value = { ...row }
  isView.value = true
  dialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除这条注册记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRegistration([row.id])
  })
}

// 批量删除
const handleBatchDelete = () => {
  const ids = selectedRows.value.map((row: any) => row.id)
  ElMessageBox.confirm(`确定要删除选中的 ${ids.length} 条注册记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRegistration(ids)
  })
}

// 导出
const handleExport = () => {
  exportRegistration()
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchRegistrationList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchRegistrationList()
}

// 弹窗成功回调
const handleDialogSuccess = () => {
  fetchRegistrationList()
}

// 初始化
onMounted(() => {
  fetchRegistrationList()
})
</script>

<style scoped>
.registration-page {
  padding: 20px;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>